package com.bizmda.bizsip.sink.processor;

import cn.hutool.json.JSONObject;
import com.bizmda.bizsip.common.BizException;
import com.bizmda.bizsip.common.BizUtils;
import com.bizmda.bizsip.config.AbstractSinkConfig;
import com.bizmda.bizsip.sink.connector.BeanSinkConnector;
import com.bizmda.bizsip.sink.connector.SinkBeanSinkConnector;
import com.bizmda.bizsip.sink.api.SinkBeanInterface;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class SinkProcessor extends AbstractSinkProcessor {
    public SinkProcessor(AbstractSinkConfig sinkConfig) {
        super(sinkConfig);
    }

    @Override
    JSONObject process(JSONObject inMessage) throws BizException {
        log.debug("sink[{}]进行default处理",this.sinkConfig.getId());
        log.trace("Sink传入消息:\n{}", BizUtils.buildJsonLog(inMessage));

        boolean isConverter = true;
        if ((this.connector.getSinkConnector() instanceof BeanSinkConnector)) {
            isConverter = false;
        } else if (this.connector.getSinkConnector() instanceof SinkBeanSinkConnector) {
            if (((SinkBeanSinkConnector) this.connector.getSinkConnector()).getSinkBean() instanceof SinkBeanInterface) {
                isConverter = false;
            }
        }

        if (!isConverter) {
            log.debug("Sink通过Connect[{}]调用服务", this.connector.getSinkConnector().getType());
            JSONObject jsonObject = this.connector.process(inMessage);
            log.trace("Sink服务返回消息:\n{}", BizUtils.buildJsonLog(jsonObject));
            return jsonObject;
        }
        log.debug("Sink调用Convert[{}]打包", this.converter.getConverter().getType());
        byte[] packedMessage = this.converter.pack(inMessage);
        log.trace("Sink打包后消息:\n{}", BizUtils.buildHexLog(packedMessage));
        log.debug("Sink通过Connect[{}]调用服务", this.connector.getSinkConnector().getType());
        byte[] returnMessage = this.connector.process(packedMessage);
        log.trace("Sink服务返回消息:\n{}", BizUtils.buildHexLog(returnMessage));
        log.debug("Sink调用Convert[{}]解包", this.converter.getConverter().getType());
        JSONObject unpackedJsonObject = this.converter.unpack(returnMessage);
        log.trace("Sink返回消息:\n{}", BizUtils.buildJsonLog(unpackedJsonObject));
        return unpackedJsonObject;
    }
}
